import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', () => {
  const accountId = ref('')
  const accountType = ref('')
  const isLoggedIn = computed(() => !!accountId.value)

  const setLogin = (id, type) => {
    accountId.value = id
    accountType.value = type
    // 保存到localStorage
    localStorage.setItem('accountId', id)
    localStorage.setItem('accountType', type)
  }

  const setLogout = () => {
    accountId.value = ''
    accountType.value = ''
    localStorage.removeItem('accountId')
    localStorage.removeItem('accountType')
  }

  // 初始化时从localStorage读取
  const initAuth = () => {
    const savedId = localStorage.getItem('accountId')
    const savedType = localStorage.getItem('accountType')
    if (savedId && savedType) {
      accountId.value = savedId
      accountType.value = savedType
    }
  }

  return {
    accountId,
    accountType,
    isLoggedIn,
    setLogin,
    setLogout,
    initAuth
  }
})